import { defineComponent } from "vue";
import { ElTable as T } from "element-plus";
import { ElTableColumn as Tcol } from "element-plus";
import Extend from "./extend.jsx";
import variables from "@/styles/variables.module.scss";
import { useI18n } from "vue-i18n";
export default defineComponent({
  name: 'STable',
  props: {
    border: {
      type: [Boolean],
      default: true,
      required: false,
    },
    columns: {
      type: [Array],
      default: function () {
        return [];
      },
      required: false,
    },
  },
  computed: {
    columnsC() {
      const index = this.columns.findIndex((item) => item.type === "langs");
      let path;
      if (index >= 0) {
        path = (this.columns.splice(index, 1)?.[0] ?? {})?.path;
      }
      const { t } = useI18n();
      const columns = this.columns.concat(this.columnExtends);
      return columns.map((item) => {
        item.align ??= "center";
        item.type !== "selection"
          ? (item.showOverflowTooltip ??= true)
          : (item.showOverflowTooltip ??= false);
        if (item.prop && path) {
          item.label = t(`${path}.${item.prop}`);
        }
        return item;
      });
    },
    columnExtends() {
      const columnExtends = [];
      const columns = this.columns;
      for (const key in columns) {
        if (columns?.[key]?.prop === "action") {
          return columnExtends;
        }
      }
      const { $slots } = this;
      if (this.$slots.action) {
        columnExtends.push({
          label: "操作",
          render(h, scope) {
            return <div>{$slots?.action?.(scope)}</div>;
          },
        });
      }
      return columnExtends;
    },
  },
  methods: {
    renderTcol() {
      const { columnsC: columns } = this;
      return (
        columns?.map((column) => {
          if (!column.render) {
            return <Tcol {...column}></Tcol>;
          } else {
            return (
              <Tcol {...column}>
                {{
                  default: (scope) => (
                    <Extend render={column.render} params={scope} />
                  ),
                }}
              </Tcol>
            );
          }
        }) ?? []
      );
    },
  },
  render() {
    const { $props, $attrs } = this;
    const headerCellStyle = `1px solid ${variables.tableHeaderColor}`;
    const props = {
      ...$props,
      ...$attrs,
      headerCellStyle: {
        borderBottom: headerCellStyle,
        borderRight: headerCellStyle,
        borderTop: headerCellStyle,
      },
    };

    return (
      <div>
        <T {...props}>{this.renderTcol()}</T>
      </div>
    );
  },
  install: function (Vue) {
    Vue.component(this.name, this);
  },
});
